import $ from 'jquery'
import 'ztree'
import qs from 'qs'

export default {
    name: 'Rolemg',
    components: {

    },
    data() {
        return {
            menuSet: 0,
            handleDialog: false,
            formDisabled: false,
            formLabelWidth: '120px',
            currentPage: 1,
            pagesize: 5,
            menuName: '',
            operateCheckActive: '',
            roleData: [],
            multipleSelection: [],
            height: '600',
            total: 0,
            form: {
                name: '',
                description: '',
                id: ''
            },
            menuData: [],//菜单
            operateData: [],//功能
            checkedMenus: [],//选择的菜单
            checkedOperate: [],//选择的功能
            subCheck: [],
            showItem: '',
            setting: {
                check: {
                    enable: true,
                    nocheckInherit: false,
                    chkboxType: { "Y": "ps", "N": "ps" }
                },
                data: {
                    simpleData: {
                        enable: true
                    },
                    key: {
                        url: "noUrl",
                        name: "mName"
                    }
                },
                callback: {
                    beforeClick: this.beforeClick,
                    onClick: this.zTreeOnClick,
                    onCheck: this.zTreeOnCheck,
                }
            }
        }
    },
    computed: {
        offset: function () {
            return (this.currentPage - 1) * this.pagesize;
        },
        selectMenu: function () {
            var menuArr = [];
            if (this.menuData == undefined || this.menuData == '') {
                operateArr.push("");
                return;
            }
            this.menuData.forEach((val, idx) => {
                var item = JSON.parse(JSON.stringify(val));
                item.checked = false;
                for (var i = 0; i < this.checkedMenus.length; i++) {
                    if (item.mid == this.checkedMenus[i]) {
                        item.checked = true;
                    }
                }
                menuArr.push(item);
            });
            return menuArr;
        },
        selectOperate: function () {
            var operateArr = [];
            if (this.operateData == undefined || this.operateData == '') {
                operateArr.push("");
                return;
            }
            this.operateData.forEach((val, idx) => {
                var item = val;
                for (let i = 0; i < this.checkedOperate.length; i++) {
                    if (item.mid == this.checkedOperate[i]) {
                        item.checked = true;
                    }
                }
                operateArr.push(item);
            });
            return operateArr;
        }
    },
    watch: {
        showItem(val, oldVal) {
            this.operateCheckActive = 'slide-fade'
        },
        handleDialog: function (newVal, oldVal) {
            if (oldVal) {
                this.menuSet = 0;
                $.fn.zTree.init($("#treeDemo"), this.setting, this.menuData).expandAll(true);
                this.form = {
                    name: '',
                    description: '',
                    id: ''
                };
                this.checkedOperate = [];
                this.formDisabled = false;
                this.subCheck = [];
            }
        }
    },
    created() {
        if (window.innerHeight <= 635) {
            this.height = 328;
        }
        this.initDialogData();
        this.initRolelist();
    },
    methods: {
        //获取菜单树
        initDialogData() {
            this.$http.get("/menuInfoController/queryMenuTree")
                .then((res) => {
                    if (res.status == 200) {
                        //判断是否为sysadmin,sysadmin则拉到全部菜单否则拉去相对于的菜单
                        var userInfo = JSON.parse(window.localStorage.getItem("userInfo"));
                        if (userInfo.name == 'sysadmin') {
                            this.menuData = res.rows;
                        } else {
                            this.menuData = this.setmIdFun(JSON.parse(window.localStorage.getItem("roleMenu")));
                        }
                        //获取功能列表数据
                        this.$http.get('/menuInfoController/queryOperateList')
                            .then((res) => {
                                if (res.status == 200) {
                                    this.operateData = res.array;
                                }
                            }).catch((err) => {
                                console.log("err", err);
                            })
                        $.fn.zTree.init($("#treeDemo"), this.setting, this.menuData).expandAll(true);
                    }
                }).catch((err) => {
                    console.log("err", err);
            });
        },
        //获取用户角色 
        initRolelist() {
            this.$http.post('/roleInfoController/findList?limit=' + this.pagesize + '&offset=' + this.offset)
                .then((res) => {
                    if (res.status == 200) {
                        this.roleData = res.rows;
                        this.total = res.total;
                    }
                }).catch((res) => {
                    console.log("err", res);
                });
        },
        deleteRow(row, event) {
            console.log(row);
            this.$confirm('删除用户[' + row.roleName + '],确定继续？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.$http.post('/roleInfoController/delRoleInfo', qs.stringify({ rId: row.rId }))
                    .then((res) => {
                        if (res.status == 200) {
                            this.$message({
                                type: 'success',
                                message: res.message
                            });
                            this.initRolelist();
                            return;
                        }
                        this.$message.error(res.message);
                    }).catch((err) => {
                        console.log("res", err)
                    });
            }).catch(() => {
                this.$message({
                    type: 'type',
                    message: '已取消操作'
                })
            });
        },
        rowClick(row, type) {
            this.form.name = row.roleName;
            this.form.description = row.description;
            this.form.id = row.rId;
            if (type == 'set') {
                this.menuSet = 2;
                this.formDisabled = true;
                //获取选中的菜单
                this.$http.post('/menuInfoController/queryMenuChecked?roleId=' + row.rId)
                    .then((res) => {
                        if (res.status == 200) {
                            this.checkedMenus = res.checkedMenus;
                            this.checkedOperate = res.checkedOperate;
                            var menuArr = JSON.parse(JSON.stringify(this.menuData));
                            this.setCheckFun(menuArr);
                            $.fn.zTree.init($("#treeDemo"), this.setting, menuArr).expandAll(true);
                        } else if (res.status == 500) {
                            this.$message.error(res.message);
                        }
                    })
                    .catch((err) => {
                        console.log(res);
                    })
            } else if (type == 'modify' || typeof (type) == 'object') {
                this.menuSet = 1;
            }
            this.handleDialog = true;
        },
        subModify() {
            var postData = {
                rId: this.form.id,
                roleName: this.form.name,
                description: this.form.description
            }
            if (postData.name == "") {
                this.$message.error("角色名称不能为空!");
                return;
            }
            //修改角色信息
            this.$http.post('/roleInfoController/updateRoleInfo', qs.stringify(postData))
                .then((res) => {
                    if (res.status == 200) {
                        this.$message({
                            type: 'success',
                            message: res.message
                        })
                        this.initRolelist();
                        this.handleDialog = false;
                        return;
                    }
                    this.$message.error(res.message);
                })
                .catch((res) => {
                    console.log(res)
                })
        },
        subAdd() {
            var postData = {
                roleName: this.form.name,
                description: this.form.description,
            }
            if (postData.roleName == '') {
                this.$message.error("角色名称不能为空！");
                return;
            }
            //新增角色
            this.$http.post('/roleInfoController/addRoleInfo', qs.stringify(postData))
                .then((res) => {
                    if (res.status == 200) {
                        this.$message({
                            type: 'success',
                            message: res.message
                        });
                        this.initRolelist();
                        this.handleDialog = false;
                        return;
                    } else if (res.status == 406) {
                        this.$message.error(res.message);
                    }
                }).catch((err) => {
                    console.log(res);
                });
        },
        subSet() {
            this.subCheck = this.checkedMenus.concat(this.checkedOperate);
            // 角色配置修改
            this.$http.post('/roleInfoController/assign', qs.stringify({ roleId: this.form.id, mIds: this.subCheck.join(',') }))
                .then((res) => {
                    if (res.status == 200) {
                        this.$message({
                            type: 'success',
                            message: res.message
                        })
                        this.handleDialog = false;
                        return;
                    }
                    this.$message.error(res.message);
                })
                .catch((res) => {
                    console.log(res)
                })
        },
        setCheckFun(data) {
            for (var i = 0; i < data.length; i++) {
                for (var j = 0; j < this.checkedMenus.length; j++) {
                    if (data[i].mid == this.checkedMenus[j]) {
                        data[i].checked = true;
                    }
                    if (data[i].children != undefined && data[i].children.length > 0) {
                        this.setCheckFun(data[i].children);
                    }
                }
            }
        },
        /* 递归增加mid字段 */
        setmIdFun(data) {
            for (var i = 0; i < data.length; i++) {
                data[i].mid = data[i].mid;
                if (data[i].children != undefined && data[i].children.length > 0) {
                    this.setmIdFun(data[i].children)
                }
            }
            return data;
        },
        handleCheckBox() {

        },
        toggleSelection(rows) {
            if (rows) {
                rows.forEach(row => {
                    this.$refs.multipleTable.toggleSelection(row);
                });
            } else {
                this.$refs.multipleTable.clearSelection();
            }
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        handleSizeChange(val) {
            this.pagesize = val;
            this.initRolelist();
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            this.initRolelist();
        },
        zTreeOnClick(event, treeId, treeNode) {
            // console.log(treeNode.tId + ", " + treeNode.name);
        },
        zTreeOnCheck(event, treeId, treeNode) {
            var _this = this;
            if (treeNode.checked) {
                this.menuName = treeNode.mName;
                this.showItem = treeNode.mid;
            }
            var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
                checkCount = zTree.getCheckedNodes(true).length,//选中
                nocheckCount = zTree.getCheckedNodes(false).length,//未选中
                changeCount = zTree.getChangeCheckedNodes().length;//获取输入框勾选状态被改变的节点集合（与原始数据 checkedOld 对比）
            var checkedNames = [], checkedIds = [], nocheckedIds = [], nocheckedNames = [];
            for (var i = 0; i <= zTree.getCheckedNodes(true).length - 1; i++) {
                checkedIds.push(zTree.getCheckedNodes(true)[i].mid);
                checkedNames.push(zTree.getCheckedNodes(true)[i].mName);
            };
            for (var i = 0; i <= zTree.getCheckedNodes(false).length - 1; i++) {
                nocheckedIds.push(zTree.getCheckedNodes(false)[i].mid);
                this.operateData.forEach((val, idx) => {
                    if (val.pId == zTree.getCheckedNodes(false)[i].mid) {
                        for (var j = 0; j < _this.checkedOperate.length; j++) {
                            if (_this.checkedOperate[j] == val.mid) {
                                _this.checkedOperate.splice(j, 1);
                                break;
                            }
                        }
                    }
                })
                nocheckedNames.push(zTree.getCheckedNodes(false)[i].mName);
            };
            this.checkedMenus = checkedIds;
        },
        beforeClick(treeId, treeNode) {
            var zTree = $.fn.zTree.getZTreeObj("treeDemo");
            if (treeNode.checked) {
                this.menuName = treeNode.mName;
                this.showItem = treeNode.mid;
            }
            //第二个参数!treeNode.checked和"",省略此参数效果等同，则根据对此节点的勾选状态进行 toggle 切换，第三个参数设置为true时候进行父子节点的勾选联动操作 ，第四个参数true 表示执行此方法时触发 beforeCheck & onCheck 事件回调函数；false 表示执行此方法时不触发事件回调函数
            return false;
        }
    },
    mounted() {
        $.fn.zTree.init($("#treeDemo"), this.setting, this.menuData).expandAll(true);
    },
}